import { useUserStore } from '@/store';
import type { CustomRequestOptions } from './requestInterceptor';
import { refreshToken } from '@/api/user';
import { useHttpFail, useHttpResolve } from '@/hooks';

export const http = <T>(options: CustomRequestOptions) => {
  // 1. 返回 Promise 对象
  return new Promise<IResData<T>>((resolve, _reject) => {
    console.log('打印***options http', options);
    uni.request({
      ...options,
      dataType: 'json',
      // #ifndef MP-WEIXIN
      responseType: 'json',
      // #endif
      // 响应成功
      async success(res) {
        useHttpResolve(res, resolve, options);
      },
      // 响应失败
      fail(err) {
        useHttpFail(resolve, err);
      }
    });
  });
};

export default {
  get: <T = any>(
    url: string,
    data?: Indexable,
    options?: CustomRequestOptions
  ) => http<T>({ url, data, ...options, method: 'GET' }),
  post: <T = any>(
    url: string,
    data: Indexable,
    options?: CustomRequestOptions
  ) => http<T>({ url, data, ...options, method: 'POST' })
};

// uni.uploadFile封装
export const uniFileUpload = <T>(options: CustomRequestOptions) => {
  // 1. 返回 Promise 对象
  return new Promise<IResData<T>>((resolve, reject) => {
    uni.uploadFile({
      ...options,
      // 响应成功
      async success(res) {
        // 状态码 2xx，参考 axios 的设计
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 文件上传接口的rea.data的类型为string，这里转一下
          const resData = JSON.parse(res.data) as IResData<T>;
          resolve(resData);
        } else if (res.statusCode === 401) {
          // 401错误  -> 清理用户信息，跳转到登录页
          useUserStore().clearUserInfo();
          // uni.navigateTo({ url: '/pages/login/login' })
          const res = await refreshToken({
            refreshToken: useUserStore().userInfo.refreshToken
          });
          console.log('打印***res', res);
          // reject(res);
        } else {
          // 其他错误 -> 根据后端错误信息轻提示
          uni.showToast({
            icon: 'none',
            title: '文件上传错误'
          });
          reject(res);
        }
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误，换个网络试试'
        });
        reject(err);
      }
    });
  });
};
